//
//  LoginViewController.m
//  NavCon2
//
//  Created by Joseph Ayo Akinyele on 3/11/10.
//  Copyright 2010 Johns Hopkins University. All rights reserved.
//

#import "LoginViewController.h"
#import "iHealthEHRAppDelegate.h"
#import "GoogleHealth.h"
#import "JHUHospital.h"
#import "UserSettings.h"
#import "SqliteInterface.h"

@implementation LoginViewController
//@synthesize label1;
@synthesize username, password, OfflineAccessLogin;
@synthesize GoogleHealthLogin, JHUHospitalLogin;
@synthesize activityIndicator;
@synthesize googlehealth, jhu;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		jhu = [[JHUHospital alloc] init];
		googlehealth = [[GoogleHealth alloc] init];
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[self.navigationController setToolbarHidden:YES];	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Help" style:UIBarButtonItemStylePlain 
																			  target:self action:@selector(helpButton)] autorelease];
    [super viewDidLoad];
}

-(void) helpButton {
	NSLog(@"Should display the help web-page here");
}

// TODO: clean up objects in preparation to be able to login twice?
- (void)viewWillAppear:(BOOL)animated {
	password.text = @"";
	[self.navigationController setToolbarHidden:YES];	
	[super viewWillAppear:animated];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	//[label1 release];
	[sql release];
	[profile release];
	[username release];
	[password release];
	[googlehealth release];
	[jhu release];
    [super dealloc];
}

#pragma mark -
#pragma mark Login UI Actions 

// Must check whether logging into Google Health or some other hospital
// if login successful, then load the next view then download the profile feed in
// the case of Google Health. For JHU Hospital, load custom view Child Controller.
-(IBAction) loginButtonPressed: (id) sender
{
	NSString *user = username.text;		
	user = [user stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[activityIndicator startAnimating];
	
	// read text fields and output in labels.
	if(self.GoogleHealthLogin == YES) {
		// NSLog(@"Login to Google Health set!");
		if ([user rangeOfString:@"@"].location == NSNotFound) {
			// if no domain was supplied, add @gmail.com
			user = [user stringByAppendingString:@"@gmail.com"];
			username.text = user;
		}
		googlehealth.gUsername = username.text;
		googlehealth.gPassword = password.text;
		// using sandbox or production? Make this a bundle setting?
		[googlehealth useGoogleHealthProduction:[UserSettings getGoogleHealthProdSetting]];
		[self fetchFeedOfProfileList];
	}
	else if(self.JHUHospitalLogin == YES) 
	{
		// NSLog(@"Login to JHU Health set!");		
		if([jhu authenticateWithHTTP:username.text andPass:password.text]) {
			NSLog(@"User authenticated successfully!");
			[jhu downloadXML];
			[self loadProfileView];
		}
		else {
			NSLog(@"User NOT authenticated!");
			// TODO: Load Alert here!
			[self loginFailed:@"User authentication failed to JHU Hospital!" withTitle:@"JHU Hospital"];
			username.text = @"";
			password.text = @"";
		}
	}
	else if(self.OfflineAccessLogin == YES)
	{
		// TODO: authenticate passphrase (username dictates which interface cached?), 
		// then pull user's data from iPhone file system
		NSLog(@"Entered Passphrase: '%@'", password.text);
		NSString *passphrase = [UserSettings getCachePassphrase];
		if([passphrase isEqualToString:password.text]) {
			// success
			NSLog(@"Retrieving encrypted record from filesystem");
			[self loadLocalProfileView:username.text];
		}
		else {
			// Notify user that password is incorrect.
			LOG_CONSOLE("User NOT authenticated for Offline Access.");
			[self loginFailed:@"User authentication failed for local record access!" withTitle:@"Offline"];
			username.text = @"";
			password.text = @"";
		}

		
	}
	
	// debug purposes 
	// label1.text = username.text;
	// label2.text = password.text;	
}

-(IBAction) removeKeyboard:(id) sender
{
	[sender resignFirstResponder];
}

-(IBAction) backgroundClick:(id) sender
{
	[username resignFirstResponder];
	[password resignFirstResponder];
}

-(IBAction) startActivityIndicator: (id) sender
{
	[activityIndicator startAnimating];
}

-(IBAction) stopActivityIndicator: (id) sender
{
	[activityIndicator stopAnimating];
}

#pragma mark -
#pragma mark Retrieve Profile Feeds from Google Health, then Loads the profile view
// begin retrieving the list of the user's profileLists
- (void)fetchFeedOfProfileList {

	googlehealth.mProfileListFeed = nil;
	GDataServiceGoogleHealth *service = [googlehealth healthService];
	NSURL *feedURL = [googlehealth getFeedURL];
	[service fetchFeedWithURL:feedURL
			 delegate:self
			 didFinishSelector:@selector(profileListFeedTicket:finishedWithFeed:error:)]; 
	
	// NSLog(@"fetchFeedWithURL: %@ [done]", [service description]);
	
}

// retrieves the profile feeds and 
// creates an array of entries, pushes into CCRViewController
// displays it.
-(void) profileListFeedTicket:(GDataServiceTicket *) ticket
             finishedWithFeed:(GDataFeedBase *) feed
                        error:(NSError *) error 
{
	
    NSLog(@"feed: %@", [feed description]);
	if(error == nil) {
		NSUInteger max = [[feed entries] count];
		if([[feed entries] count] > 0) {
			NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:max];
			/* Retrieve the names of the profile list feeds (try for loop?) */
			// GDataEntryBase *entry = [[feed entries] objectAtIndex:0];
			// NSArray *profileFeeds = [feed entries];
			// profileName = [[entry title] stringValue];
			//NSString *log = [[NSString alloc] initWithFormat:@"profileFeeds: %@", [[entry title] stringValue]];
			//NSLog(@"profile status: %@", log);
			
			// save for future, if 
			if(googlehealth.mProfileListFeed != nil) 
				NSLog(@"mProfileListFeed not null! Releasing memory");
  		    googlehealth.mProfileListFeed = [feed retain];

			GDataEntryBase *entry;
			NSString *item;
			for(int i = 0; i < (int) max; i++) {
				entry = [[googlehealth.mProfileListFeed entries] objectAtIndex:i];
				item = [[entry title] stringValue];
				NSLog(@"feed items: %@", item);
				[array insertObject:item atIndex:i];
			}

			if(ccrViewController == nil) {
				ccrViewController =  //[[CCRViewController alloc] initWithNibName:nil bundle:nil];
					[[CCRViewController alloc] initWithStyle: UITableViewStyleGrouped];
			}
			ccrViewController.title = @"Family Profiles";
			ccrViewController.myProfileList = array;
			ccrViewController.googlehealth = googlehealth;
			
			iHealthEHRAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
			[delegate.navController pushViewController:ccrViewController animated:YES];
			/* verify list 
			for(int j = 0; j < [array count]; j++)
				NSLog(@"replay: %@", [array objectAtIndex:j]); */
			[array release];
		}
	}
	else {
		// clean up here?
	    NSLog(@"Alert user that an error occured when retrieving profile list feed.");
		[self loginFailed:@"Authentication failed! Check username or password and try again." withTitle:@"Google Health"];
		username.text = @"";
		password.text = @"";
	}
	[activityIndicator stopAnimating];
}

#pragma mark -
#pragma mark JHU Hospital 
-(void) loadProfileView
{
	NSDictionary *dictProfile = jhu.ccrEntries;
	// jhu.xmlData 
	// after download, construct array of ccr objects mapped to user's profile
#ifdef HEALTH_DEBUG
	for(id key in d) {
		for(int i = 0; i < [[dictProfile objectForKey:key] count]; i++)
			NSLog(@"Profile => %@, Entry => %@", key, [[[dictProfile objectForKey:key] objectAtIndex:i] ccrsection]);
	}
#endif
	if(customViewController == nil) {
		customViewController = [[CustCCRViewController alloc] initWithStyle: UITableViewStyleGrouped];
	}
	
	customViewController.title = @"Your Profile";
	customViewController.profile = dictProfile;
	customViewController.jhu = jhu;
	iHealthEHRAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.navController pushViewController:customViewController animated:YES];
	[activityIndicator stopAnimating];
}

#pragma mark -
#pragma mark Offline Interface
-(void) loadLocalProfileView:(NSString *) user
{
	// see if user has cached any records.
	if(sql == nil) {
		sql = [[SqliteInterface alloc] initWith:user];
	}
	else { /* not the first time a user has logged in */
		[sql release];
		sql = [[SqliteInterface alloc] initWith:user];
	}

	[sql createRecordTable];	
	NSArray *key = [[NSArray alloc] initWithObjects:@"CONDITION", @"MEDICATION",
						  @"ALLERGY", @"PROCEDURE", @"LABTEST", @"IMMUNIZATION", @"PAYER", nil];
	BOOL _cacheExists = NO;
	NSMutableArray *ccrEntries = [[NSMutableArray alloc] init];
	NSLog(@"Get cached encrypted CCRs...");
	for(int i = 0; i < [key count]; i++) {
		NSArray *ccrObjects = [sql retrieveCCR:[key objectAtIndex:i]];
		if(ccrObjects != nil) {
			for (int i = 0; i < [ccrObjects count]; i++) {
				CCRObject *c = [ccrObjects objectAtIndex:i];
				[c printObject];
				// add each ccr entry in the returned array into 'ccrEntries'
				[ccrEntries addObject:c];
				_cacheExists = YES;
			}
			[ccrObjects release];
		}
	}
	[key release];
	
	if(!_cacheExists) {
		// user has not cached any records..notify them here...
		UIAlertView *status = [[UIAlertView alloc] initWithTitle:@"Not Found" message:@"Cannot find your records! Cache your records through the Google Health Interface"
														delegate:self cancelButtonTitle:nil 
											   otherButtonTitles:@"OK", nil];
		[status show];
		[status release];	
		[activityIndicator stopAnimating];
		return;
	}
	
	
	// should have built up all the ccr entries into 'ccrEntries' array
	if(profile != nil)
		[profile release];
	profile = [[NSDictionary alloc] initWithObjectsAndKeys:ccrEntries, user, nil]; 
		
	// if not already allocated, do so here
	if(offlineViewController == nil) {
		offlineViewController = [[OffCCRViewController alloc] initWithStyle:UITableViewStyleGrouped];
	}
	// store sql object and profile name and load view
	offlineViewController.title = @"Your Profile";
	offlineViewController.profile = profile;
	
	iHealthEHRAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.navController pushViewController:offlineViewController animated:YES];
	
	[activityIndicator stopAnimating];
}

-(void) loginFailed:(NSString *) message withTitle:(NSString *) mytitle
{
	UIAlertView *fail = [[UIAlertView alloc] initWithTitle:mytitle message:message
												delegate:self cancelButtonTitle:nil 
												otherButtonTitles:@"OK", nil];
	[fail show];
	[fail release];
}

@end
